package event.model;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import event.model.database.Database;

public class Dsek {

	public static final int ATTENDING = 1;
	public static final int NOT_ATTENDING = -1;
	public static final int NOT_ACCEPTED = 0;
	
	private Database db;

	public Dsek() {
		db = new Database();
	}


	public ArrayList<Event> getEvents() {
		ArrayList<Event> events = new ArrayList<Event>();

		ResultSet result = db
				.query("SELECT * FROM registration_events WHERE (opens <= UNIX_TIMESTAMP() AND closes >= UNIX_TIMESTAMP() )");

		try {
			while (result.next()) {
				DsekEvent e = new DsekEvent();

				e.title = result.getString("title");
				e.info = result.getString("description");
				e.eventStarts = new Time(result.getLong("begins")*1000);
				e.registrationClose = new Time(result.getLong("locks")*1000);
				e.id = result.getInt("id");
				e.spots = result.getInt("limit");
				if (e.spots != 0) {
					ResultSet numGoes = db.query("SELECT COUNT( * ) AS antal FROM registration_registrations WHERE event =" + e.id);
					numGoes.next();
					e.going = numGoes.getInt("antal");
				}
				e.approval = result.getString("requireApproval").equals("yes");	
				
				
				e.arranger = new User(result.getInt("responsible"));
				events.add(e);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return events;
	}
	
	/**
	 * Returns a user id which corresponds to the card id passed as an argument.
	 * 
	 * @param cardId
	 * @return
	 */
	public int getIdFromCardId(String cardId){
		ResultSet rs = db.query("SELECT * FROM rfid WHERE rfid=" + cardId + " LIMIT 1");
		
		int user_id = -1;
		try {
			if (rs.next())
				user_id = rs.getInt("user_id");
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return user_id;
	}
	
	/**
	 * Performs a "SELECT * FROM members WHERE id=user_id" and returns
	 * the result set for the recipient to parse.
	 * @param user_id
	 * @return
	 */
	public ResultSet getUserInfo(int user_id){
		ResultSet rs = db.query("SELECT * FROM members WHERE id=" + user_id + " LIMIT 1");
		return rs;
	}

	public int attendingStatus(User u, Event e) {
		int event = ((DsekEvent) e).id;
		int person = u.getId();
		String query = "SELECT approved FROM registration_registrations WHERE person = " + person + " AND event = " + event + " LIMIT 1";
		
		ResultSet answer = db.query(query);
		
		try {
			if (answer.next()) {
				return answer.getString("approved").equals("yes") ? ATTENDING : NOT_ACCEPTED;
			}
		} catch (SQLException e1) {
			e1.printStackTrace();
		}
		return NOT_ATTENDING;
		
	}
	
	/**
	 * Adds a specific user to an event.
	 * @param u the user to ad
	 * @param e an event
	 * @return true if could add, false otherwise
	 */
	public int addUserToEvent(User u, Event e) {
		int event = ((DsekEvent) e).id;
		int person = u.getId();
		String allergies = u.getAllergies();
		String comment = "---Added from the wallpc Narwhal!---";
		String approved = e.requiresApproval() ? "no" : "yes";
		long registrationdate = System.currentTimeMillis()/1000;
		
		// INSERT INTO registration_registrations(person, event, registrationdate, allergies, alcohol, comment, approved, type) VALUES('$me', '$id', UNIX_TIMESTAMP(), '$allergies', '$alcohol', '$comment', '$approved','$type')
		String query = "INSERT INTO registration_registrations (person, event, registrationdate, allergies, comment, approved) " +
						"VALUES (" + person + ", " + event + ", " + registrationdate + ", '" + allergies + "', '" + comment + "', '" + approved + "')";
		int updateResponse = db.update(query);
		return updateResponse;
	}
	
	
	private class DsekEvent implements Event {

		
		private int id;
		private Time eventStarts;
		private Time registrationClose;
		private String title;
		private String info;
		private int spots;
		private int going;
		private User arranger;
		private boolean approval;
		
		private DsekEvent() {
		}

		@Override
		public String getInfo() {
			return info;
		}

		@Override
		public String getTitle() {
			return title;
		}

		@Override
		public boolean isOpen() {
			return registrationClose.compareTo(new Time()) > 0;
		}

		@Override
		public int getFreeSpots() {
			return spots-going;
		}

		@Override
		public int getSpots() {
			return spots;
		}

		@Override
		public String getWhen() {
			return eventStarts.toString();
		}

		@Override
		public String getCloses() {
			return registrationClose.toString();
		}

		@Override
		public User getArranges() {
			return arranger;
		}

		@Override
		public boolean requiresApproval() {
			return approval;
		}

	}


	public void uppdateUsed(int user_id) {
		String query = "UPDATE rfid SET last_used = UNIX_TIMESTAMP() WHERE user_id = " + user_id + " LIMIT 1";
		db.update(query);
	}
}
